// API基础配置
const API_BASE_URL = 'https://api.molipai.vip/api/v1';

// 请求拦截器
const requestInterceptor = (config: any) => {
  // 添加token到请求头
  const token = wx.getStorageSync('accessToken');
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`,
    };
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response: any) => {
  if (response.statusCode === 401) {
    // token过期，清除本地存储并跳转到登录页
    wx.removeStorageSync('accessToken');
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('tokenType');
    
    wx.showToast({
      title: '登录已过期，请重新登录',
      icon: 'error'
    });
    
    setTimeout(() => {
      wx.redirectTo({
        url: '/pages/qrlogin/qrlogin'
      });
    }, 1500);
  } else if (response.statusCode === 403) {
    // 403错误，需要调用miniprogramLogin
    console.log('检测到403错误，需要重新登录');
    // 这里不直接处理，让调用方决定如何处理
  }
  return response;
};

// 通用请求方法
const request = (options: any): Promise<any> => {
  return new Promise((resolve, reject) => {
    const config = requestInterceptor(options);
    
    wx.request({
      ...config,
      success: (res) => {
        const response = responseInterceptor(res);
        console.log('sss',res);
        
        if (response.statusCode >= 200 && response.statusCode < 300) {
          resolve(response.data);
        } else {
          // 返回包含状态码的错误信息
          reject({
            statusCode: response.statusCode,
            message: `请求失败: ${response.statusCode}`,
            data: response.data
          });
        }
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
};

// 扫码登录相关API
export const qrLoginAPI = {
  // 生成二维码
  generateQRCode: () => {
    return request({
      url: `${API_BASE_URL}/auth/qrcode/generate`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      }
    });
  },

  // 检查登录状态
  checkLoginStatus: (sessionId: string) => {
    return request({
      url: `${API_BASE_URL}/auth/qrcode/status/${sessionId}`,
      method: 'GET'
    });
  },

  // 确认登录（小程序端调用）
  confirmLogin: (sessionId: string, userInfo: any) => {
    return request({
      url: `${API_BASE_URL}/auth/qrcode/confirm`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        session_id: sessionId,
        user_info: userInfo
      }
    });
  },

  // 小程序扫码登录
  miniprogramLogin: (scene: string, code: string, userInfo: any) => {
    return request({
      url: `${API_BASE_URL}/auth/qrcode/miniprogram-login`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        scene: scene,
        code: code,
        user_info: userInfo
      }
    });
  }
};

// 用户相关API
export const userAPI = {
  // 获取用户信息
  getUserInfo: () => {
    return request({
      url: `${API_BASE_URL}/auth/me`,
      method: 'GET'
    });
  },

  // 更新用户信息
  updateUserInfo: (userInfo: any) => {
    return request({
      url: `${API_BASE_URL}/user/profile`,
      method: 'PUT',
      header: {
        'Content-Type': 'application/json'
      },
      data: userInfo
    });
  },

  // 获取用户资料可见性设置
  getProfileVisibility: () => {
    return request({
      url: `${API_BASE_URL}/auth/profile-visibility`,
      method: 'GET'
    });
  },

  // 更新用户资料可见性设置
  updateProfileVisibility: (showProfile: boolean) => {
    return request({
      url: `${API_BASE_URL}/auth/profile-visibility`,
      method: 'PUT',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        show_profile: showProfile
      }
    });
  }
};

// 更新个人信息API
export const updateProfile = (profileData: {
  nickname: string;
  // avatar: string;
  qq_number: string;
}) => {
  return request({
    url: `${API_BASE_URL}/auth/profile`,
    method: 'PUT',
    header: {
      'Content-Type': 'application/json'
    },
    data: profileData
  });
};

// 拍卖相关API
export const auctionAPI = {
  // 获取拍卖商品列表
  getAuctionItems: (skip: number = 0, limit: number = 10, category?: string, keyword?: string, status?: string) => {
    let url = `${API_BASE_URL}/auction/items/public?skip=${skip}&limit=${limit}`;
    
    // 添加分类参数
    if (category && category !== 'all') {
      url += `&category=${encodeURIComponent(category)}`;
    }
    
    // 添加搜索关键词参数
    if (keyword && keyword.trim()) {
      url += `&keyword=${encodeURIComponent(keyword.trim())}`;
    }
    
    // 添加状态参数
    if (status && status !== 'all') {
      url += `&status=${encodeURIComponent(status)}`;
    }
    
    return request({
      url,
      method: 'GET'
    });
  },

  // 获取拍卖商品详情
  getAuctionItemDetail: (itemId: number) => {
    return request({
      url: `${API_BASE_URL}/auction/items/${itemId}`,
      method: 'GET'
    });
  },

  // 参与竞价
  placeBid: (itemId: number, bidAmount: number) => {
    return request({
      url: `${API_BASE_URL}/auction/items/${itemId}/bid`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        amount: bidAmount
      }
    });
  }
};

export default {
  request,
  qrLoginAPI,
  userAPI,
  auctionAPI
}; 